package org.atf.mgr;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.management.Notification;

import org.atf.services.TaskStatus;
import org.atf.utils.ATFUtils;

import com.ibm.websphere.management.NotificationConstants;

public class WASNotificationImpl extends ATFNotifications{
	List<TaskStatus>  notifications = new ArrayList<TaskStatus>();
	int defaultNotificationSize= 100;
	public void handleNotification(Notification notification, Object handback) {
		// TODO Auto-generated method stub
		System.out.println(notification);
		TaskStatus ts= new TaskStatus();
		Calendar cal=Calendar.getInstance();
		cal.setTimeInMillis(notification.getTimeStamp());
		ts.setStartDate(cal.getTime());
		ts.setEndDate(cal.getTime());
		String type=notification.getType().replaceAll(NotificationConstants.TYPE_PROCESS+".", "").toUpperCase();
		ts.setComment(type);
		String source=notification.getSource().toString();
		source=source.replaceAll("\\{","");
		source=source.replaceAll("\\}", "");
		//System.out.println("source: "+source);
		String[] sourceArray=source.split(",");
		String cellName = "";
		String nodeName = "";
		for(String st:sourceArray){
			String[] stArry=st.split("=");
			if(stArry.length > 1){
				if(stArry[0].trim().equalsIgnoreCase("cell")){
					cellName =stArry[1].trim();
				}
				if(stArry[0].trim().equalsIgnoreCase("node")){
					nodeName =stArry[1].trim();
				}
				
			}
		}
		String userData=notification.getUserData().toString();
		System.out.println("userData: "+userData);
		userData=userData.replaceAll("\\{","");
		userData=userData.replaceAll("\\}", "");
		//System.out.println(userData);
		String[] stringArray=userData.split(",");
		for(String st:stringArray){
			String[] stArry=st.split("=");
			if(stArry.length > 1){
				if(stArry[0].trim().equalsIgnoreCase("processName")){
					String serverName =stArry[1].trim();
					ts.setServerName(serverName);
					break;
				}
				
			}	
		}
		ATFUtils.updateServerStatus(cellName,nodeName, ts.getServerName(),type);
		notifications.add(ts);
	}

	@Override
	public List<TaskStatus> getNotifications() {
		// TODO Auto-generated method stub
		return notifications;
	}

	@Override
	public void clearNotifications() {
		// TODO Auto-generated method stub
		notifications.clear();
	}

	@Override
	public void addNotification(TaskStatus ts) {
		// TODO Auto-generated method stub
		if(notifications.size() < defaultNotificationSize ){
			notifications.add(ts);
		}
	}

}
